const http = require('http');
const querystring = require('querystring');
const dns = require('dns');
var logger = require('./log4js.js');

var client  = {};
 
// 向服务端发送请求
client.send = function (url,data,method,callback,error)
{

  var postData = querystring.stringify(data);

  if(!isURL(url)){
    logger.warn('url不正确:'+url);
    callback(null);
    return;
  }
  
 
  

  var url = parse(url);


 // console.log(JSON.stringify(url));
  //return;
// 用于请求的选项
  var options = {
     host: url.host,
     port: url.port,
     path: url.path,
     method : method,
     timeout : 10,
     headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'Content-Length': Buffer.byteLength(postData)
    }
  };

  var req = http.request(options, function(response){
     // 不断更新数据
    var receives = [];
    response.on('data', function(data) {
      receives.push(data);
    });
    response.on('end', function() {
      var resData = Buffer.concat(receives).toString();
      callback(resData);
    });
   
  });
	req.on('error', function(err){
	  error(err);
	});
  	req.write(postData);
  	req.end();
  
}

/**
 * [解析url]
 * @param  {[type]} url [description]
 * @return {[type]}     [description]
 */
function parse(url) {
    
    var host = url.split('//')[1].split('/')[0];
    var path = url.substr(url.indexOf(host)+host.length);
    var port=80;

    if(host.indexOf(":")!= -1){
      
        var temp = host.split(':');
        host = temp[0];
        port = temp[1];
    }
    
    return {host:host,path:path,port:port};
}

function isURL (str_url) { 
  str_url = str_url.trim(' ');
  var reg =/^((http|https):\/\/)?[\w-_.:]+(\/[\w-_.:?&]+)*\/?$/;
  return reg.test(str_url);

}

module.exports=client;  

